#include "Port.h"

TFT_eSPI tft = TFT_eSPI();

lv_indev_state_t touch_state;
uint16_t touchX, touchY, X, Y;

uint16_t calData[5] = {386, 3180, 418, 3150, 5};

void touchpad_read(lv_indev_drv_t *indev_driver, lv_indev_data_t *data)
{
    bool touched = tft.getTouch(&touchX, &touchY, 600);
    if (!touched)
    {
        data->state = LV_INDEV_STATE_REL;
    }
    else
    {
        data->state = LV_INDEV_STATE_PR;
        X = touchX;
        Y = map(touchY, 0, 240, 240, 0);
        data->point.x = X;
        data->point.y = Y;
        // Serial.print("X:");
        // Serial.print(X);
        // Serial.print("\t");
        // Serial.print("Y:");
        // Serial.println(Y);
    }
}

static void disp_flush(lv_disp_drv_t *disp_drv, const lv_area_t *area, lv_color_t *color_p)
{
    uint32_t w = (area->x2 - area->x1 + 1);
    uint32_t h = (area->y2 - area->y1 + 1);
    tft.startWrite();
    tft.setAddrWindow(area->x1, area->y1, w, h);
    tft.pushColors((uint16_t *)&color_p->full, w * h, true);
    tft.endWrite();
    lv_disp_flush_ready(disp_drv);
}

void lv_port_disp_init(void)
{
    Backlight_Init();

    tft.begin();
    tft.setRotation(1);
    
    tft.setTouch(calData);
    tft.fillScreen(TFT_BLACK);
    // tft.writecommand(ST7789_DISPOFF);

    lv_init();
    
    static lv_disp_draw_buf_t draw_buf_dsc;
    static lv_color_t buf_1[MY_DISP_HOR_RES * 10];
    static lv_color_t buf_2[MY_DISP_HOR_RES * 10];
    lv_disp_draw_buf_init(&draw_buf_dsc, buf_1, buf_2, MY_DISP_HOR_RES * 10);

    static lv_disp_drv_t disp_drv;
    lv_disp_drv_init(&disp_drv);
    disp_drv.hor_res = MY_DISP_HOR_RES;
    disp_drv.ver_res = MY_DISP_VER_RES;
    disp_drv.flush_cb = disp_flush;
    disp_drv.draw_buf = &draw_buf_dsc;
    lv_disp_drv_register(&disp_drv);

    static lv_indev_drv_t indev_drv;
    lv_indev_drv_init(&indev_drv);
    indev_drv.type = LV_INDEV_TYPE_POINTER;
    indev_drv.read_cb = touchpad_read;
    lv_indev_drv_register(&indev_drv);

    delay(200);
    tft.writecommand(ST7789_DISPON);
    Backlight_SetValue(1024);
}